package com.i.template.interceptor;

import com.i.template.constant.RedisConstants;
import com.i.template.util.HttpUtils;
import com.i.template.util.JWTUtils;
import com.i.template.util.UserHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * @author lewis
 * @type class
 * @description
 * @since 2024/7/25
 */
//@Component
public class LoginInterceptor implements HandlerInterceptor {
    private StringRedisTemplate redisTemplate;
    public LoginInterceptor(StringRedisTemplate redisTemplate){
        this.redisTemplate = redisTemplate;
    }
    //TODO: 刷新redis存储key的时间
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // UV统计
//        redisTemplate.opsForHyperLogLog().add(RedisConstants.VISIT_COUNT, HttpUtils.getIpAddr(request));
        String token = request.getHeader("token");
        Object uid = JWTUtils.parseToken(token).getClaim("uid");
        UserHolder.setUser(Long.valueOf(uid.toString()));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.clear();
    }
}
